package cn.jhoncy.jproject.framework.security.Authorization;

import cn.jhoncy.jproject.system.entity.SysPower;
import cn.jhoncy.jproject.system.mapper.SysPowerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 授权:资源角色授权器
 * Created by zhuangqi on 17-4-17.
 */
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private SysPowerMapper sysPowerMapper;

    private Map<String, Collection<ConfigAttribute>> resourceMap;
    public static boolean databaseChanged = true;

    //提取系统中的所有权限
    private void loadResourceMatchAuthority() {
        List<SysPower> powers = sysPowerMapper.selectAll();
        resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
        for (SysPower power : powers){
            Collection<ConfigAttribute> list = new ArrayList<ConfigAttribute>();
            if (resourceMap.containsKey(power.getMenuUrl())){
                list = resourceMap.get(power.getMenuUrl());
                list.add(new SecurityConfig(power.getRoleName()));
                resourceMap.put(power.getMenuUrl(),list);
            } else {
                list.add(new SecurityConfig(power.getRoleName()));
                resourceMap.put(power.getMenuUrl(),list);
            }
        }
        databaseChanged = false;
    }

    // 根据URL，找到相关的权限配置。
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation fi = (FilterInvocation) object;
        HttpServletRequest request = fi.getRequest();
        System.out.println("================【requestUrl is ：" + fi.getRequestUrl()+"】==================");
        if (resourceMap == null || databaseChanged) {
            loadResourceMatchAuthority();
        }
        Collection<ConfigAttribute> attrs = new ArrayList<ConfigAttribute>();
        for (String urlPattern : resourceMap.keySet()) {
            //路径匹配器
            AntPathRequestMatcher matcher = new AntPathRequestMatcher(urlPattern);
            if (matcher.matches(request)) {
                System.out.println("matched resource url patterns: " + urlPattern);
                attrs.addAll(resourceMap.get(urlPattern));
            }
        }
        return attrs;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
